package com.yonyou.common.service.messagecenter.rabbitmq.service;

import java.io.UnsupportedEncodingException;

import org.springframework.stereotype.Service;

import com.yonyou.common.service.messagecenter.rabbitmq.entity.MessageProtocol;
import com.yonyou.common.service.messagecenter.rabbitmq.entity.MessageProtocolDto;
import com.yonyou.common.service.messagecenter.util.MqConsts;

@Service
public class MessageProtocolService {
    public MessageProtocolDto parseConsumerData(byte[] body,String consumer) throws UnsupportedEncodingException{
		String data1 = new String(body, "UTF-8");
		String[] datas=data1.split(MqConsts.MES_PLACE_HOLDER);
		String data=datas[0];
		String sign=datas[1];
		String appid=datas[2];
		MessageProtocolDto mes=new MessageProtocolDto();
		mes.setAppid(appid);
		mes.setData(data);
		mes.setSign(sign);
		mes.setEndPointName(consumer);
		return mes;
    }
    public MessageProtocol getMessageProtocol(MessageProtocolDto mes){
    	MessageProtocol protocol=new MessageProtocol();
    	protocol.setAppid(mes.getAppid());
    	protocol.setMessagecontent(mes.getData());
    	protocol.setSign(mes.getSign());
    	return protocol;
    }

    public String formatProduceData(MessageProtocol messageProtocol){
    	String data=messageProtocol.getMessagecontent();
    	data=data.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("$", "-");
		int b=0,e=data.length();
    	if(String.valueOf(data.charAt(0)).equals("["))
    		b=1;
    	if(String.valueOf(data.charAt(data.length()-1)).equals("]"))
    		e=e-1;
		data=data.substring(b, e)+MqConsts.MES_PLACE_HOLDER+messageProtocol.getSign()+MqConsts.MES_PLACE_HOLDER+messageProtocol.getAppid();
		messageProtocol.setMessagecontent(data);
		return data;
    }
}
